from django.contrib.auth import (
    login as django_login,
    logout as django_logout
)
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.csrf import csrf_exempt

from rest_framework import viewsets, mixins, status, permissions
from rest_framework.decorators import action
from rest_framework.response import Response

from user.serializers import RegisterSerializer, LoginSerializer, \
    UserDetailsSerializer, JWTSerializer, PasswordChangeSerializer
from user.models import User


def jwt_encode(user):
    try:
        from rest_framework_jwt.settings import api_settings
    except ImportError:
        raise ImportError("djangorestframework_jwt needs to be installed")

    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

    payload = jwt_payload_handler(user)
    return jwt_encode_handler(payload)


class UserViewSet(viewsets.GenericViewSet):
    queryset = User.objects.none()

    def get_serializer_class(self):
        if self.action == 'registration' or self.action == 'registration_multi':
            return RegisterSerializer
        elif self.action == 'login':
            return LoginSerializer
        elif self.action == 'change_password':
            return PasswordChangeSerializer
        return UserDetailsSerializer

    @action(['post'], detail=False, permission_classes=[permissions.AllowAny])
    def registration(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        user = serializer.save(self.request)
        token = jwt_encode(user)

        data = {
            'user': user,
            'token': token
        }
        response_data = JWTSerializer(data).data

        return Response(response_data,
                        status=status.HTTP_201_CREATED)


    @action(['post'], detail=False, permission_classes=[permissions.AllowAny])
    @csrf_exempt
    def login(self, request):
        serializer = self.get_serializer(data=request.data,
                                         context={'request': request})
        serializer.is_valid(raise_exception=True)

        user = serializer.validated_data['user']
        token = jwt_encode(user)
        if getattr(settings, 'REST_SESSION_LOGIN', True):
            django_login(request, user)

        data = {
            'user': user,
            'token': token
        }
        response_serializer = JWTSerializer(data, context={'request': self.request})
        return Response(response_serializer.data, status=status.HTTP_200_OK)

    @action(['post'], detail=False, permission_classes=[permissions.IsAuthenticated])
    def logout(self, request):
        try:
            request.user.auth_token.delete()
        except (AttributeError, ObjectDoesNotExist):
            pass

        django_logout(request)

        return Response({"detail": "退出登录成功"},
                        status=status.HTTP_200_OK)

    @action(['get'], detail=False,
            permission_classes=[permissions.IsAuthenticated],
            url_path='detail', url_name='user-detail')
    def detail_info(self, request):
        user = request.user
        serializer = self.get_serializer(user)
        return Response(serializer.data)

    @action(['post'], detail=False, permission_classes=[permissions.IsAuthenticated],
            url_path='change-password', url_name='change-password')
    def change_password(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"detail": "密码修改成功"})


    @action(['post'], detail=False, url_path='registration_multi', url_name='change-password', permission_classes=[permissions.AllowAny])
    def registration_multi(self, request):
        from utils.tools import create_phone, make_random_time
        from datetime import datetime
        import random
        from user.models import UserAccessRecord
        pathChoice = [
            '/',
            '',
            '/login',
            '/regsiter',
            '/home',
            '/task',
            '/report',
            '/plantform',
            '',
            '/'
        ]
        mothedChoice = [
            'GET',
            'GET',
            'GET',
            'POST',
            'PUT',
            'DELETE',
            'GET',
            'GET',
            'GET'
        ]
        for i in range(30):
            data = {
                'mobile': create_phone(),
                'password1': '123123',
                'password2': '123123'
            }
            serializer = self.get_serializer(data=data)
            serializer.is_valid(raise_exception=True)
            user = serializer.save(data)
            # 先创建用户随机访问次数
            random_access_time = []
            for i in range(random.randint(15,250)):
                random_access_time.append(make_random_time())
            # 然后进行排序
            random_access_time = sorted(random_access_time)
            # 然后加入访问记录
            for access_time in random_access_time:
                record = UserAccessRecord()
                record.user = user
                record.access_path = random.choice(pathChoice)
                record.refer_path = random.choice(pathChoice)
                record.access_method = random.choice(mothedChoice)
                record.access_time = access_time
                record.username = user.mobile
                record.save()
            user.last_login = random_access_time[-1]
            user.date_joined = random_access_time[0]
            user.save()
            print(user, i)

        return Response({"success": True},
                        status=status.HTTP_201_CREATED)
